package com.suisui.symmetric;

import com.suisui.util.HexUtils;
import org.junit.Test;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;

/**
 * 测试加密模式和填充模式
 */
public class AesTest2 {
    //字符编码
    private static final String UTF8 = StandardCharsets.UTF_8.name();
    /**
     * AES默认填充模式：PKCS7Padding，分组的加密模式ECB
     */
    //算法名字
     private static final String ALGORITHM = "AES/ECB/PKCS7Padding";
    //private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
    private static final String ALGORITHM_TYPE = "AES";
    //IV 默认长度16
    //private static final String IV = "1234569874569852";
    //密钥，默认长度16/24/32
    private static final String KEY = "1234567869854985";


    @Test
    public void test1() throws Exception {
        String str = "数据测试！";
        String encrypt = encrypt(str);
        //71ef0cf6320139d79192850bc0a2c067
        System.out.println("加密后数据：" + encrypt);
        String decrypt = decrypt(encrypt);
        System.out.println("解密后数据：" + decrypt);
    }


    /**
     * 加密
     * @param text 待加密的内容
     */
    public String encrypt(String text) throws Exception {
        Cipher cipher = getCipherSimple(Cipher.ENCRYPT_MODE, KEY);
        byte[] encodeBytes = cipher.doFinal(text.getBytes(UTF8));
        return HexUtils.convertBytes2HexStr(encodeBytes);
    }
    /**
     * 解密
     * @param encodeText 加密后的字符串
     */
    public String decrypt(String encodeText) throws Exception {
        //加密后的字符串进行16进制转换
        byte[] hex2Bytes = HexUtils.convertHex2Bytes(encodeText);
        //解密
        Cipher cipher = getCipherSimple(Cipher.DECRYPT_MODE, KEY);
        byte[] decode = cipher.doFinal(hex2Bytes);
        return new String(decode,UTF8);
    }

    /**
     * 获取cipher对象，对传入的seed长度有要求
     * des：要求seed字节数为8
     * aes：要求sed字节数为16/24/32
     * @param type 加解密模式
     * @param seed 密钥key
     * @return
     */
    public Cipher getCipherSimple(int type,String seed) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKeySpec secretKey = new SecretKeySpec(seed.getBytes(UTF8), ALGORITHM_TYPE);
        cipher.init(type,secretKey);
        //IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes(UTF8));
        //初始化(使用CBC加密模式时，需要多传一个ivParameterSpec)
        //cipher.init(type,secretKey,ivParameterSpec);
        return cipher;
    }

}
